package com.example.capsule_chat0322.netty;


import android.content.Context;

import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.bean.ViewMessage;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.global.GlobalThreadPool;
import com.example.capsule_chat0322.listener.NettyGroupMessageListener;

import org.greenrobot.eventbus.EventBus;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/27 20:15
 */
public class NettyClient {

    public NettyManage nettyManage;


    private NettyClient() {
        nettyManage = new NettyManage(new NettyGroupMessageListener());
    }


    private static class NettyClientBuilder {

        private static final NettyClient INSTANCE = new NettyClient();

    }

    public static NettyClient getInstance() {
        return NettyClientBuilder.INSTANCE;
    }


    public void connectServer(Context context) throws InterruptedException {
        String isConnect = System.getProperty("isConnect");
        if (isConnect == null || isConnect.equals("false")) {
            nettyManage.connect(Constant.HOST, Constant.PORT,context);
        }
    }


    public void sendMessage(MessageBean messageBean) {

        GlobalThreadPool.buildThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    nettyManage.doSendMessage(messageBean, new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (future.isSuccess() && messageBean.getActionType() == 1) {
                                EventBus.getDefault().post(new ViewMessage("发送成功~"));
                            } else if (messageBean.getActionType() == 1) {
                                EventBus.getDefault().post(new ViewMessage("发送失败!   " + future.get()));
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    public void shutdown() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                nettyManage.doShutdown();
            }
        }).start();

    }


}
